import sys
import platform

if platform.system()=='Windows':
    sys.path.append('d:\\pythonworkspace\\st\\nextt')


from rqalpha.apis import *

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    context.s1 = context.config.base.universe[0]
    context.s2 = context.config.base.universe[1]
    context.s3 = context.config.base.universe[2]
    context.s4 = context.config.base.universe[3]
    context.s5 = context.config.base.universe[4]
    context.s6 = context.config.base.universe[5]
    context.s7 = context.config.base.universe[6]
    context.s8 = context.config.base.universe[7]

    # 设置滚动窗口
    context.H = context.config.params.H
    context.R = context.config.params.R

    # 设置全局计数器
    context.counter = context.H
    context.window = context.R + 1

    # 初始化时订阅合约行情。订阅之后的合约行情会在handle_bar中进行更新
    subscribe(context.config.base.universe)


# before_trading此函数会在每天交易开始前被调用，当天只会被调用一次
def before_trading(context):
    # 样例商品期货在回测区间内有夜盘交易,所以在每日开盘前将计数器清零
    pass


# 你选择的期货数据更新将会触发此段逻辑，例如日线或分钟线更新
def handle_bar(context, bar_dict):

    context.counter += 1
    # 当累积满一定数量的bar数据时候,进行交易逻辑的判断
    if context.counter > context.H:
        # 复位
        context.counter = 1
        # 获取当前一对合约的仓位情况。如尚未有仓位,则对应持仓量都为0
        long_pos_dict = {}
        for s in context.config.base.universe:
            long_pos_dict[s] = get_position(s, POSITION_DIRECTION.LONG)
        short_pos_dict = {}
        for s in context.config.base.universe:
            short_pos_dict[s] = get_position(s, POSITION_DIRECTION.SHORT)

        # 获取当前bar对应合约的收盘价格
        price_a = bar_dict[context.s1].close
        price_b = bar_dict[context.s8].close

        # 获取当天历史日线价格队列
        price_incs_dict = {}
        for s in context.config.base.universe:
            price_array = history_bars(s, context.window, '1d', 'close')
            price_incs_dict[s] = (price_array[context.R] - price_array[0]) / price_array[0]
        #
        price_incs_dict = dict(sorted(price_incs_dict.items(), key=lambda item: item[1]))
        print(price_incs_dict)

        buy_list = list(price_incs_dict.keys())[-2:]
        sell_list = list(price_incs_dict.keys())[:2]
        # 先平仓
        for k,v in long_pos_dict.items():
            if v.quantity > 0 and k not in buy_list:
                sell_close(k, v.quantity)
                logger.info('买入仓位%s平仓成功' % k)
        for k,v in short_pos_dict.items():
            if v.quantity > 0 and k not in sell_list:
                buy_close(k, v.quantity)
                logger.info('卖出仓位%s平仓成功' % k)
        # 后开仓
        for k,v in long_pos_dict.items():
            if v.quantity <= 0 and k in buy_list:
                buy_open(k, 1)
                logger.info('买入仓位%s创建成功' % k)
        for k,v in short_pos_dict.items():
            if v.quantity <= 0 and k in sell_list:
                sell_open(k, 1)
                logger.info('卖出仓位%s创建成功' % k)
        pass


config = {
  "params": {
    "R": 10,
    "H": 15
  },
  "base": {
    "universe": ['AG1612', 'AU1612', 'AL1612', 'CU1612', 'ZN1612', 'PB1612', 'NI1612', 'SN1612'],
    "start_date": "2016-05-01",
    "end_date": "2016-12-15",
    "accounts": {
        "future": 1000000
    }
  },
  "extra": {
    "log_level": "error",
  },
  "mod": {
    "sys_analyser": {
      "benchmark": "000300.XSHG",
      "enabled": True,
      "plot": True
    }
  }
}


if __name__ == '__main__':
    import json
    # # 您可以指定您要传递的参数
    # from rqalpha import run_func
    # ret = run_func(init=init, before_trading=before_trading, handle_bar=handle_bar, config=config)
    # print(ret)
    # 批量回测
    from nextt.tasks import group_file_task
    batch_params = [{"R":5, "H":5}, {"R":5, "H":10}, {"R":5, "H":15},
                    {"R":10, "H":5}, {"R":10, "H":10}, {"R":10, "H":15},
                    {"R":15, "H":5}, {"R":15, "H":10}, {"R":15, "H":15}]
    ret = group_file_task(__file__, batch_params, config)
    print(json.dumps(ret, indent=2))